#!/bin/bash

while getopts "PShv" Option
do
 case $Option in
  h ) echo "Usage: `basename $0`"\
       "[-h] [-v] [-P] [-S] data_file1.octxt [data_file2.octxt] [data_file.mat]"
      echo "Convert files from octave format to matlab format."
      echo
      echo "  -P  preprocess the file(s) with \"fix_octave_notation\""
      echo "  -S  transform a series of files separately: the input"
      echo "      argument must be enclosed in quotes \" \" and each file"
      echo "      is then converted separately"
      echo "  -h  display this help"
      echo "  -v  verbose mode"
      exit;;
  P ) require_preprocessing=1;;
  S ) convert_series=1;;
  v ) verbose=1;;
 esac
done
shift $(($OPTIND - 1))


flags=""

# check verbose
if [ ! ${verbose} ]
 then
  gen_opt="--silent"
else
  gen_opt="--echo-commands"
  flags="${flags} -v"
fi

# check preprocessing
if [ ${require_preprocessing} ]
 then
  flags="${flags} -P"
fi

if [ ! ${convert_series} ]
 then

  # define output file name
  if [ $# -eq 1 ]
   then
    in_fn=$1
    out_fn=`echo $1 | sed 's/\.octxt$/.mat/'`
  else
    in_fn=""
    for ((i=1; i <= $#-1 ; i++))
     do
      eval in_fni=\${$i}
      in_fn="${in_fn}${in_fni} "
    done
    eval out_fn=\${$#}
  fi
  
  if [ ${verbose} ]
   then
    echo "Input file(s): ${in_fn}"
    echo "Output file:   ${out_fn}"
  fi
  
  # check output
  if [ -e ${out_fn} ]
   then
    echo "Error: output file \"${out_fn}\" already exists!"
    exit
  fi
  
  # call octave
  { 
    for in_fni in ${in_fn}
     do
      if [ ${require_preprocessing} ]
       then
        `dirname $0`/fix_octave_notation ${in_fni}
      fi
      echo load ${in_fni}
    done
    # we don't want to save __nargin__ so we proceed as follows:
    # 1) get a list of all variables (including __nargin__)
    echo "OCTXT2MAT_LIST_OF_ALL_THE_VARIABLES = who('-variables');"
    # 2) assuming __nargin__ is the first variable, save the others 
    echo "save('-mat','${out_fn}',OCTXT2MAT_LIST_OF_ALL_THE_VARIABLES{2:end});"
  } | octave ${gen_opt}

else

  if [ $# -eq 1 ]
   then
    for in_file in `ls $1`
     do
      $0 ${flags} ${in_file}
    done
  else
    echo "Wrong number of arguments: $#"
    echo "When using -S only one input arguments is allowed;"
    echo "  check that filenames are passed into quotes!"
    exit 1
  fi
fi
